package me.leiusual.sharing.ui.mine

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import cn.sharesdk.framework.Platform
import cn.sharesdk.onekeyshare.OnekeyShare
import cn.sharesdk.wechat.friends.Wechat
import cn.sharesdk.wechat.moments.WechatMoments
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_mine_invite.*
import me.leiusual.sharing.BuildConfig
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.InviteQRCode
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.util.extension.setQRCode
import me.leiusual.sharing.util.extension.toast
import timber.log.Timber
import javax.inject.Inject

/**
 * Create by leiusual on 2018/7/16
 */
class MineInviteFragment : DaggerFragment() {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: MineInviteViewModel by viewModels { factory }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_mine_invite, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }
    toolbar.setOnMenuItemClickListener {
      showShareApp()
      true
    }

    text_view_invited.setOnClickListener {
      val userId = viewModel.user.userIdInClient
      val navDirections = MineInviteFragmentDirections.actionMineInviteFragmentToMineInvitedFragment(userId, userId)
      findNavController().navigate(navDirections)
    }

    text_view_invite_copy.setOnClickListener {
      val clipboardManager = context?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
      val text = text_view_invite_code.text
      clipboardManager.primaryClip = ClipData.newPlainText(null, text)
      toast("已复制")
    }

    button_invite.setOnClickListener {
      showShare()
    }

    observeData()

    viewModel.inviteQRCode()
  }

  private fun observeData() {
    viewModel.inviteQRCode.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("inviteQRCode = %s", it)
      when (it) {
        is Data.Loading -> {
          layout_invite_info.visibility = View.GONE
          content_loading_progress_bar.show()
        }
        is Data.Error -> {
          content_loading_progress_bar.hide()
          toast(it.error.message)
        }
        is Data.Success -> {
          content_loading_progress_bar.hide()
          val data = it.data
          if (data.success && data.qrCode != null) {

            layout_root.setBackgroundResource(R.drawable.bg_layout_invite_shape)
            toolbar.background = null

            layout_invite_info.visibility = View.VISIBLE
            val qrCode = Uri.parse(data.qrCode)
            image_view_qr_code.setQRCode(qrCode.toString())
            text_view_invite_code.text = qrCode.getQueryParameter("ic")
          } else {

            layout_invite_fail.visibility = View.VISIBLE
            text_view_message.text = data.errorMsg
          }
        }
      }
    })
  }

  private fun showShareApp() {

    val data = viewModel.inviteQRCode.value as? Data.Success<InviteQRCode.Response> ?: return
    val url = data.data.appUrl ?: "https://www.lingling9.com/"

    try {
      val oks = OnekeyShare()
      oks.disableSSOWhenAuthorize()
      oks.setTitle(getString(R.string.app_name))
      oks.text = BuildConfig.VERSION_NAME
      oks.setUrl(url)
      oks.setShareContentCustomizeCallback { platform, shareParams ->
        when (platform.name) {
          Wechat.NAME, WechatMoments.NAME -> {
            shareParams.shareType = Platform.SHARE_WEBPAGE
          }
        }
      }
      oks.show(context)
    } catch (e: Exception) {
      Timber.w(e)
    }
  }

  private fun showShare() {

    val data = viewModel.inviteQRCode.value as? Data.Success<InviteQRCode.Response> ?: return
    val url = data.data.qrCode

    try {
      val oks = OnekeyShare()
      oks.disableSSOWhenAuthorize()
      oks.setTitle(getString(R.string.app_name))
      oks.text = "我推荐码${text_view_invite_code.text}"
      oks.setUrl(url)
      oks.setShareContentCustomizeCallback { platform, shareParams ->
        when (platform.name) {
          Wechat.NAME, WechatMoments.NAME -> {
            shareParams.shareType = Platform.SHARE_WEBPAGE
          }
        }
      }
      oks.show(context)
    } catch (e: Exception) {
      Timber.w(e)
    }
  }
}